import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import {Form, Input, InputNumber, Radio, Modal, Select, Upload, message, Switch, TreeSelect} from 'antd'
import {t, Trans} from "@lingui/macro"
import QuillEditor from "../../../components/Editor/QuillEditor";
import TextArea from "antd/es/input/TextArea";
import draft from "draft-js";
import store from "store";
import api from '../../../services/api'
import style from './Modal.less'
import ImgCrop from "antd-img-crop";

const {createAdminContentImage} = api

const {ContentState} = draft
const FormItem = Form.Item

const formItemLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 14,
  },
}

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

function beforeUpload(file) {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
}

class AdminContentModal extends PureComponent {
  formRef = React.createRef()

  state = {
    value: [],
    loading: false, //上传 loading
    imageUrl: null,
  };

  //头像上传句柄
  handleChange = info => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      //设置表单值
      this.formRef.current.setFieldsValue({thumbnail: info.file.response.payload})
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, imageUrl =>
        this.setState({
          imageUrl,
          loading: false,
        }),
      );
    }
  };

  handleOk = () => {
    const { item = {}, onOk } = this.props
    this.formRef.current.validateFields()
      .then(values => {
        const data = {
          ...values,
          id: item.id,
          status: values.status == true ? 1 : 0,
          isTop: values.isTop == true ? 1 :0,
          thumbnail: values.thumbnail == null ? item.thumbnail : values.thumbnail
        }
        console.log(data)
        onOk(data)
      })
      .catch(errorInfo => {
        console.log(errorInfo)
      })
  }

  upload = (file) => {
    let token = store.get('token')
    return new Promise(
      (resolve, reject) => {
        let formData = new FormData()
        formData.append('thumbnail', file)
        fetch(createAdminContentImage, {
          method: 'POST',
          headers: {
            'Authorization': token
          },
          body: formData,
        }).then(res => {
          return res.json()
        }).then(res => {
          if (res.code !== 2000) {
            message.error('图片上传失败', 2)
            reject(res)
          } else {
            resolve({data: {link: res.payload}})
          }

        }).catch(err => {
          reject(err)
        })
      })
  }

  render() {
    const { item = {}, onOk, form, categoryTree, ...modalProps } = this.props
    let imageUrl = this.state.imageUrl
    if(item.thumbnail != null && imageUrl == null) {
      imageUrl = item.thumbnail
    }

    let token = store.get('token')
    return (

      <Modal {...modalProps} onOk={this.handleOk} width={1300}>
        <Form ref={this.formRef} name="control-ref" initialValues={{ ...item, status:item.status==1?true:false,isTop:item.isTop==1?true:false }} layout="horizontal">

         <FormItem name='title' rules={[{ required: true }]}
            label={t`title`} hasFeedback {...formItemLayout}>
            <Input />
          </FormItem>
          <FormItem name='keywords' rules={[{ required: false }]}
                                        label={t`Keywords`} hasFeedback {...formItemLayout}>
          <Input />
        </FormItem>
         <FormItem name='description' rules={[{ required: false }]}
            label={t`Description`} hasFeedback {...formItemLayout}>
            <TextArea />
          </FormItem>

         <FormItem name='categoryId' rules={[{ required: true }]}
            label={t`Category`} hasFeedback {...formItemLayout}>
           <TreeSelect
             style={{ width: '100%' }}
             // value={value}
             dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
             treeData={categoryTree}
             placeholder="Please select category"
             treeDefaultExpandAll
           />
          </FormItem>
         <FormItem name='status' rules={[{ required: true }]}
                   valuePropName="checked"
            label={t`status`} hasFeedback {...formItemLayout}>
           <Switch checkedChildren="开启" unCheckedChildren="关闭" />
          </FormItem>
         <FormItem name='isTop' rules={[{ required: true }]}
                   valuePropName="checked"
            label={t`Is Top`} hasFeedback {...formItemLayout}>
           <Switch checkedChildren="开启" unCheckedChildren="关闭" />
          </FormItem>

          <FormItem name='thumbnail' rules={[{ required: false }]}
                    label={t`Thumbnail`} hasFeedback {...formItemLayout}>
            <ImgCrop rotate>

              <Upload
                name="thumbnail"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action={createAdminContentImage}
                beforeUpload={beforeUpload}
                onChange={this.handleChange}
                headers={{Authorization:token}}
              >
                {imageUrl ? <img src={imageUrl} alt="thumbnail" style={{ width: '100%' }} /> : null}
              </Upload>

            </ImgCrop>
          </FormItem>

          <FormItem name='body' rules={[{ required: false }]}
                    label={t`Body`} hasFeedback {...formItemLayout}>



            <QuillEditor />

          </FormItem>
        </Form>
      </Modal>
    )
  }
}

AdminContentModal.propTypes = {
  type: PropTypes.string,
  item: PropTypes.object,
  onOk: PropTypes.func,
}

export default AdminContentModal

